import axios from 'axios'
import qs from 'qs'
import { Message } from 'element-ui'
import store from '@/store/'
import { getAccessToken, getUserToken } from '@/api/app'
import { aesSign } from '@/api/crypto'

// create an axios instance
// axios.defaults.bizServerUrl = window.CONFIG.bizServerUrl
axios.defaults.timeout = window.CONFIG.timeout
// request interceptor
axios.interceptors.request.use(
  config => {
    if (getAccessToken()) {
      config.headers['access-token'] = getAccessToken() // 让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
    } else {
      console.log('get access token is null !!!')
    }
    if (Constants.userToken) {
      config.headers['user-token'] = aesSign(Constants.userToken)
    } else {
      console.log('get user token is null !!!')
    }
    // if (config.data) {
    //   config.data = JSON.parse(Utils.htmlEscape(JSON.stringify(config.data)))
    // }
    // if (config.params) {
    //   config.params = JSON.parse(Utils.htmlEscape(JSON.stringify(config.params)))
    // }
    // Do something before request is sent config.headers['X-Token'] = getToken()
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response interceptor
axios.interceptors.response.use(
  response => response,
  /**
   * 下面的注释为通过在response里，自定义code来标示请求状态
   * 当code返回如下情况则说明权限有问题，登出并返回到登录页
   * 如想通过 xmlhttprequest 来状态码标识 逻辑可写在下面error中
   * 以下代码均为样例，请结合自生需求加以修改，若不需要，则可删除
   */
  // response => {
  //   const res = response.data
  //   if (res.code !== 20000) {
  //     Message({
  //       message: res.message,
  //       type: 'error',
  //       duration: 5 * 1000
  //     })
  //     // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
  //     if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
  //       // 请自行在引入 MessageBox
  //       // import { Message, MessageBox } from 'element-ui'
  //       MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
  //         confirmButtonText: '重新登录',
  //         cancelButtonText: '取消',
  //         type: 'warning'
  //       }).then(() => {
  //         store.dispatch('FedLogOut').then(() => {
  //           location.reload() // 为了重新实例化vue-router对象 避免bug
  //         })
  //       })
  //     }
  //     return Promise.reject('error')
  //   } else {
  //     return response.data
  //   }
  // },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default axios

/** *************************************************************************************************
 ************************************** 以下代码暂未用到 *********************************************
 ***************************************************************************************************/

function historyRecordAPI(trade, status, tradeEn, statusEn) {
  var data = {
    event: 'EventHistoryRecord',
    data: {
      'serviceType': trade,
      'status': status,
      'serviceTypeEn': tradeEn,
      'statusEn': statusEn
    }
  }
  window.parent.postMessage(data, '*')
}

/**
 * get 方法封装
 * @param url
 * @param data
 * @returns {Promise}
 */
export function get(url, params) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: qs.stringify(params)
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err.data)
    })
  })
}
/**
 * post 方法封装
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post(url, data = {}, codeName, codeNameEn) {
  data['h_bizCode'] = codeName
  store.commit('addString', data)
  return new Promise((resolve, reject) => {
    axios.post(url, qs.stringify(store.getters.getRequestData))
      .then(response => {
        resolve(response.data)
        if (codeName) {
          if (response.data.h_tranStatus === 'Y') {
            historyRecordAPI(codeName, '交易成功', codeNameEn, 'Successful trade')
          } else if (response.data.h_tranStatus === 'S') {
            historyRecordAPI(codeName, '交易部分成功', codeNameEn, 'The deal was partially successful')
          } else {
            historyRecordAPI(codeName, '查询失败', codeNameEn, 'Failed query')
          }
        }
      }, err => {
        reject(err)
        if (codeName) {
          historyRecordAPI(codeName, '请求异常', codeNameEn, 'Request exception')
        }
      })
  })
}
/**
 * post 没有包头的post方法封装
 * @param url
 * @param data
 * @returns {Promise}
 */
export function postNoHeader(url, data = {}, codeName, codeNameEn) {
  data['h_bizCode'] = codeName
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then(response => {
        resolve(response.data)
        if (codeName) {
          if (response.data.resultCode === '000000') {
            historyRecordAPI(codeName, '查询成功', codeNameEn, 'Successful Inquiry')
          } else {
            historyRecordAPI(codeName, '查询失败', codeNameEn, 'Failed Inquiry')
          }
        }
      }, err => {
        reject(err)
        if (codeName || codeNameEn) {
          historyRecordAPI(codeName, '请求异常', codeNameEn, 'Request exception')
        }
      })
  })
}
/**
 * get 方法封装
 * @param url
 * @param data
 * @returns {Promise}
 */
export function getNoHeader(url, params, paramsEn) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: qs.stringify(params, paramsEn)
    }).then(res => {
      resolve(res.data)
      if (params || paramsEn) {
        if (res.data.resultCode === '000000') {
          historyRecordAPI(params, '查询成功', paramsEn, 'Successful Inquiry')
        } else {
          historyRecordAPI(params, '查询失败', paramsEn, 'Failed Inquiry')
        }
      }
    }).catch(err => {
      reject(err.data)
      if (params || paramsEn) {
        historyRecordAPI(params, '请求异常', paramsEn, 'Request exception')
      }
    })
  })
}
